package com.appspot.androidquote.webapp.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.appspot.androidquote.webapp.Entities.MessageEntity;

@SuppressWarnings("unchecked")
public enum MessageDao {
	INSTANCE;
	
	public List<MessageEntity> getAllMessages() {
		EntityManager em = EMFService.get().createEntityManager();
		Query q = em.createQuery("SELECT M FROM MessageEntity M order by category");
		List<MessageEntity> messages = q.getResultList();
		return messages;
	}
	
	public void add(MessageEntity message) {
		synchronized (this) {
			EntityManager em = EMFService.get().createEntityManager();
			em.persist(message);
			em.close();
		}
	}
	
	public List<MessageEntity> getMessagesByCategory(String category) {
		EntityManager em = EMFService.get().createEntityManager();
		Query q = em.createQuery("SELECT M FROM MessageEntity M WHERE M.category = :P_CATEGORY");
		q.setParameter("P_CATEGORY", category);
		List<MessageEntity> messages = q.getResultList();
		return messages;
	}
	
	public void removeMessage(Long id) {
		EntityManager em = EMFService.get().createEntityManager();
		try {
			MessageEntity message = em.find(MessageEntity.class, id);
			em.remove(message);
		}
		finally {
			em.close();
		}
	}
	
}
